package org.glorylight.hacks.social.service;

import java.util.ArrayList;
import java.util.List;

import org.glorylight.hacks.social.data.UserData;
import org.glorylight.hacks.social.model.User;
import org.glorylight.hacks.social.util.ModelHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class UserService extends BaseService {
	
	private static final Logger log = LoggerFactory.getLogger(UserService.class);
	
	@Transactional(readOnly = false)
	public void addUser(UserData userData) {
		if (log.isDebugEnabled())
			log.debug("adding new user for: {}", userData.getEmailAddress());
		add(ModelHelper.convertUserData(userData));
	}
	
	@Transactional(readOnly = false)
	public void deleteUser(UserData userData) {
		if (log.isDebugEnabled())
			log.debug("delete user for: {}", userData.getEmailAddress());
		User user = findUser(userData.getEmailAddress());
		delete(user);
	}

	public UserData find(String email) {
		if (log.isDebugEnabled())
			log.debug("retrieve user: {}", email);
		User user = findUser(email);
		if (user != null)
			return ModelHelper.convertUser(user);
		else
			return null;
	}
	
	private User findUser(String email) {
		if (log.isDebugEnabled())
			log.debug("retrieve user: {}", email);
		return em.find(User.class, email);
	}

	public List<UserData> findAll() {
		if (log.isDebugEnabled())
			log.debug("find all user");
		List<User> users = em.createQuery("from User", User.class).getResultList();
		List<UserData> datas = null;
		if (users.size() > 0){
			datas = new ArrayList<UserData>();
			for (User u : users)
				datas.add(ModelHelper.convertUser(u));
		}
		
		return datas;
	}
	
}
